//
//  GLFormViewController.m
//  KTools
//
//  Created by 121 on 2017/9/28.
//  Copyright © 2017年 杭州吉利控股信息中心. All rights reserved.
//

#import "GLFormViewController.h"
#import "GLFormSection.h"
#import "GLFormRow.h"
#import "GLForm.h"
#import "GLPickerView.h"
#import "GLCustomCell.h"

#import "MJRefresh.h"

#import "Masonry.h"


@interface GLFormViewController ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation GLFormViewController

-(instancetype)init{
    self = [super init];
    if (self) {
        self.immediRefresh = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
#ifdef GLFORM_NEED_SHOW_CORNER
    _showCornerForm = GLFORM_NEED_SHOW_CORNER;
#else
    _showCornerForm = NO;
#endif
    [self gl_UIInit];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UIInit
-(void)gl_UIInit{
    
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.view);
        if (self.showCornerForm) {
            make.left.equalTo(self.view).offset(10);
            make.right.equalTo(self.view).offset(-10);
        }else{
            make.right.left.equalTo(self.view);
        }

    }];
    
//    if (self.showCornerForm) {
//        self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -5);
//    }
#ifdef GLS_COLOR_BG_GRAY_EFEFF4
    self.view.backgroundColor = GLS_COLOR_BG_GRAY_EFEFF4;
#else
    self.view.backgroundColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1];
#endif
    self.tableView.backgroundColor = self.view.backgroundColor;
    
    [self gl_setupRefresh];
}
-(void)formRow:(GLFormRow*)row eventClicked:(id)send subTag:(NSString*)subTag{}


#pragma mark- api
-(NSArray<GLFormRow *> *)formRowsWithTag:(NSString *)tag{
    NSMutableArray* array = [NSMutableArray arrayWithCapacity:0];
    for (GLFormSection* section in self.form.sectioins) {
        for (GLFormRow* row in section.rows) {
            if ([row.tag isEqualToString:tag]) {
                [array addObject:row];
            }
        }
    }
    
    return array;
}
-(GLFormRow *)formRowAtIndex:(NSIndexPath *)indexPath{
    if ((self.form.sectioins.count > indexPath.section) && [[self.form.sectioins objectAtIndex:indexPath.section] rows].count > indexPath.row){
        return [[[self.form.sectioins objectAtIndex:indexPath.section] rows] objectAtIndex:indexPath.row];
    }
    return nil;
}

-(NSIndexPath *)indexPathForFormRow:(GLFormRow *)formRow{
    
    for (NSInteger section = 0;section < self.form.sectioins.count;section++) {
        GLFormSection* formSection = [self.form.sectioins objectAtIndex:section];
        
        NSInteger row = [formSection.rows indexOfObject:formRow];
        if (row != NSNotFound) {
            return [NSIndexPath indexPathForRow:row inSection:section];
        }
    }
    return nil;
}

- (void)reloadFormRow:(GLFormRow*)row{
    NSIndexPath* indexPath = [self indexPathForFormRow:row];
    if (!indexPath) {
        return;
    }
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)reloadFormSection:(GLFormSection*)section{
    NSInteger index = [self IndexformSection:section];
    if (index != NSNotFound) {
        [self reloadSection:index];
    }
}

- (void)reloadSection:(NSUInteger)section{
    [self reloadSections:[NSIndexSet indexSetWithIndex:section]];
}
- (void)reloadSections:(NSIndexSet *)sections{
    [self.tableView reloadSections:sections withRowAnimation:UITableViewRowAnimationNone];
}
- (void)reloadData{
    [self.tableView reloadData];
}

-(GLFormSection *)formSectionAtIndex:(NSUInteger)index{
    return [self.form.sectioins objectAtIndex:index];
}

-(NSInteger)IndexformSection:(GLFormSection*)section{
    return [self.form.sectioins indexOfObject:section];
}

#pragma mark- values about
-(GLFormError*)validateFormValues{
    GLFormError* error = nil;
    for (GLFormSection* section in self.form.sectioins) {
        for (GLFormRow* row in section.rows) {
            if (row.isRequried && (!row.value || ([row.value isKindOfClass:[NSString class]] && [(NSString*)row.value isEqualToString:@""]))) {
                NSString* errmsg = row.requriedMsg;
                
                error = [GLFormError errorWithDomain:errmsg?errmsg:@"value can't been nil" code:GLErrorCodeValueNil userInfo:nil];
                error.tag = row.tag;
                return error;
            }
            
            if (!row.validateValueBlock){
                continue;
            }
            NSString* errMsg = row.validateValueBlock(row,row.value);
            if (errMsg) {
                error = [GLFormError errorWithDomain:errMsg code:GLErrorCodeValueValid userInfo:nil];
                error.tag = row.tag;
                return error;
            }
            
        }
    }
    return nil;
}

-(NSDictionary *)formValues{
    NSMutableDictionary* values = [NSMutableDictionary dictionaryWithCapacity:0];
    for (GLFormSection* section in self.form.sectioins) {
        for (GLFormRow* row in section.rows) {
            if (!row.tag || [row.tag isEqualToString:@""]) {
                continue;
            }
            if (!row.value) {
                continue;
            }
            [values setValue:row.value forKey:row.tag];
        }
    }
    return values;
}

#pragma mark - tableviewDataSource && tableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.form.sectioins.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    GLFormSection* formsection = self.form.sectioins[section];
    return formsection.rows.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GLFormSection* formsection = self.form.sectioins[indexPath.section];
    
    GLFormRow* row = [formsection.rows objectAtIndex:indexPath.row];
    row.form = self;
    
    GLFormBaseCell* cell = [row cellForFormTableView:tableView];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GLFormSection* formsection = self.form.sectioins[indexPath.section];
    GLFormRow* row = [formsection.rows objectAtIndex:indexPath.row];
    
    [self formRowClicked:row];
    if (row.action == GLFormRowActionPicker) {
        [GLPickerView showDatas:row.options convert:nil competion:^(GLPickerEvent event, id value) {
            if (event == GLPickerEventSure) {
                [row setRowValue:value];
            }
        }];
    }
    else if (row.action == GLFormRowActionPushViewController) {
        if (!self.navigationController){
            NSLog(@"GLFormRowActionPush navigationController can't been nil");
        }
        if (self.navigationController && row.pushViewController) {
            if ([row.pushViewController isKindOfClass:[NSString class]]) {
                Class pushClass = NSClassFromString(row.pushViewController);
                if (pushClass) {
                    [self.navigationController pushViewController:[[pushClass alloc]init] animated:YES];
                }
                else{
                    NSLog(@"error pushViewController is nil");
                }
            }
        }
    }
    else if (row.action == GLFormRowActionPushInput){
        if (!self.navigationController){
            NSLog(@"GLFormRowActionPush navigationController can't been nil");
        }
        GLFormOptionViewController* ctl = [[GLFormOptionViewController alloc]init];
        ctl.actionType = row.action;
        ctl.formRow = row;
        [self.navigationController pushViewController:ctl animated:YES];
    }
    else if (row.action == GLFormRowActionPushOption) {
        if (!self.navigationController){
            NSLog(@"GLFormRowActionPush navigationController can't been nil");
        }
        GLFormOptionViewController* ctl = [[GLFormOptionViewController alloc]init];
        ctl.actionType = row.action;
        ctl.options = row.options;
        ctl.formRow = row;
        [self.navigationController pushViewController:ctl animated:YES];
    }
//    else if (row.action == GLFormRowActionPushSwitch) {
//        if (!self.navigationController){
//            NSLog(@"GLFormRowActionPush navigationController can't been nil");
//        }
//        GLFormOptionViewController* ctl = [[GLFormOptionViewController alloc]init];
//        ctl.actionType = row.action;
//        ctl.formRow = row;
//        [self.navigationController pushViewController:ctl animated:YES];
//    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GLFormSection* formsection = self.form.sectioins[indexPath.section];
    GLFormRow* row = [formsection.rows objectAtIndex:indexPath.row];
    
    return row.rowHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    GLFormSection* formsection = self.form.sectioins[section];

    return formsection.HeaderHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    GLFormSection* formsection = self.form.sectioins[section];
    if (section == self.form.sectioins.count -1 && formsection.footerHeight < 1) {
        return 15.0f;
    }
    return formsection.footerHeight;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    GLFormSection* formsection = self.form.sectioins[section];
    NSString* title = formsection.tag;
    if (title) {
        return title;
    }

    return nil;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    GLFormSection* formsection = self.form.sectioins[section];
    return formsection.headerView;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    GLFormSection* formsection = self.form.sectioins[section];
    return formsection.footerView;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.showCornerForm) {
        [self resetCellAll:cell];
        
        GLFormSection* formsection = self.form.sectioins[indexPath.section];
        if (formsection.rows.count == 1) {
            [self clipCellAll:cell];
        }else{
            if (indexPath.row == 0) {
                [self clipCellTop:cell];
            }
            else if (indexPath.row == formsection.rows.count-1){
                [self clipCellBottom:cell];
                
            }
        }
    }
    
    if ([cell respondsToSelector:@selector(resetSeparatorInset)]) {
        [(GLFormBaseCell*)cell resetSeparatorInset];
    }

}

- (void)clipCellTop:(UIView *)view
{
    //将要显示cell的时候对其进行裁剪
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 1.0/[UIScreen mainScreen].scale, view.bounds.size.width, view.bounds.size.height) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
}

- (void)clipCellBottom:(UIView *)view
{
    //将要显示cell的时候对其进行裁剪
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height-1.0/[UIScreen mainScreen].scale) byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
    
}

- (void)clipCellAll:(UIView *)view
{
    CGFloat lineWidth = 1.0/[UIScreen mainScreen].scale;
    CGRect frame = CGRectMake(0, lineWidth, view.bounds.size.width, view.bounds.size.height-2*lineWidth);
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
}

- (void)resetCellAll:(UIView *)view
{
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(0, 0)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
}

-(void)formRowClicked:(GLFormRow*)row{
    
}

#pragma mark- setter and getter
-(UITableView*)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(void)setForm:(GLForm *)form{
    if (_form != form) {
        _form = form;
        if(_form.formHeaderView){
            _tableView.tableHeaderView = _form.formHeaderView;
        }else{
            UIView* v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.001)];
            _tableView.tableHeaderView = v;
        }
        if(_form.formFooterView){
            _tableView.tableFooterView = _form.formFooterView;
        }else{
            UIView* v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.001)];
            _tableView.tableFooterView = v;
        }
        
        
        if (_tableView) {
            [_tableView reloadData];
        }
    }
}

-(void)setHideLoadMore:(BOOL)hideLoadMore{
    _hideLoadMore = hideLoadMore;
    if (self.tableView.mj_footer) {
        self.tableView.mj_footer.hidden = _hideLoadMore;
    }
}
#pragma mark- pullrefresh

- (void)gl_setupRefresh{
    if (self.shouldPullRefresh) {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(gl_formPullRefresh)];
        self.tableView.mj_header.automaticallyChangeAlpha = YES;
        if (_immediRefresh) {
            [self.tableView.mj_header beginRefreshing];
        }
    }
    
    if (self.shouldLoadMore) {
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(gl_formLoadMoreData)];
    }
    
    
}


- (void)gl_formPullRefresh{
    [self formShouldReloadData];
}

- (void)gl_formLoadMoreData{
    [self formShouldLoadMoreData];
}

- (void)endRefresh{
    if (self.tableView.mj_header) {
        [self.tableView.mj_header endRefreshing];
    }
}
- (void)endLoadMore{
    if (self.tableView.mj_footer) {
        [self.tableView.mj_footer endRefreshing];
    }
}
//需要子类实现操作
-(void)formShouldLoadMoreData{}
-(void)formShouldReloadData{}



@end

@implementation GLFormError
@end;

#pragma mark- GLFormOptionViewController
@interface GLFormOptionViewController(){
    NSInteger _selectIndex;
}
@end
@implementation GLFormOptionViewController
-(void)viewDidLoad{
    [super viewDidLoad];
    _selectIndex = 0;
    [self configForm];
}

-(void)configForm{
    GLForm* form = [GLForm formWithTag:@"form"];
    switch (self.actionType) {
        case GLFormRowActionPushOption:
        {
            
            NSArray* array = (NSArray*)self.options;
            for(NSString* title in array){
                if (self.formRow && [self.formRow.value isEqualToString:title]) {
                    _selectIndex = [array indexOfObject:title];
                }
            }
            
            GLFormSection* section = [GLFormSection formSectionWithTag:@""];
            for(NSString* title in array){
                GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellText,GLCustomCellRadio] withTag:@"option"];
                [row1 addConfigValue:title componentKey:GLCustomCellText forKeyPath:nil];
                row1.valueKey = GLCustomCellRadio;
                if (_selectIndex == [array indexOfObject:title]) {
                    row1.value = [NSNumber numberWithBool:YES];
                }else{
                    row1.value = [NSNumber numberWithBool:NO];
                }
                
                [section addFormRow:row1];
            }
            [form addFormSection:section];
            break;
        }
//        case GLFormRowActionPushSwitch:
//        {
//
//            BOOL yesOrNot = [self.formRow.value boolValue];
//            GLFormSection* section = [GLFormSection formSectionWithTag:@""];
//            GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellText,GLCustomCellSwitch] withTag:@"switch"];
//            [row1 addConfigValue:self.title componentKey:GLCustomCellText forKeyPath:nil];
//            row1.value = [NSNumber numberWithBool:yesOrNot];
//
//            [section addFormRow:row1];
//            [form addFormSection:section];
//            break;
//        }
        case GLFormRowActionPushInput:
        {
            GLFormSection* section = [GLFormSection formSectionWithTag:@""];
            GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellInput] withTag:@"input"];
            row1.valueKey = GLCustomCellInput;
            row1.value = self.formRow.value;
           
            [section addFormRow:row1];
            [form addFormSection:section];
            break;
        }
        default:
            break;
    }
    
    self.form = form;
}

- (void)formRowClicked:(GLFormRow*)row{
    [super formRowClicked:row];
    if (self.actionType == GLFormRowActionPushOption) {
        
        NSArray* rows = [self formRowsWithTag:@"option"];
        for (GLFormRow* aRow in rows) {
            if (aRow == row) {
                _selectIndex = [self indexPathForFormRow:row].row;
                [aRow setRowValue:[NSNumber numberWithBool:YES]];
                
            }else{
                [aRow setRowValue:[NSNumber numberWithBool:NO]];
            }
        }
    }
}

-(void)formRow:(GLFormRow*)row eventClicked:(id)sender subTag:(NSString*)subTag{
    NSLog(@"eventClicked--->%@---%@",sender,subTag);
    
}

-(void)dealloc{
    if (self.formRow) {
        switch (self.actionType) {
            case GLFormRowActionPushOption:
            {
                
                NSString* value = self.options[_selectIndex];
                [self.formRow setRowValue:value?value:@""];
                break;
            }
//            case GLFormRowActionPushSwitch:
//            {
//
//                GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellText,GLCustomCellSwitch] withTag:@"switch"];
//
//                break;
//            }
            case GLFormRowActionPushInput:
            {
                NSDictionary* values = [self formValues];
                NSString* value = values[@"input"];
                [self.formRow setRowValue:value?value:@""];
                
                break;
            }
            default:
                break;
        }
    }
}

@end
